﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Web.Security;
using Recon.Portal.Business;
using Recon.Portal.DataObjects;

namespace Recon.Portal.WebUI
{
    public partial class UserMaster : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (((User)Session["CurrentUserVO"]) == null)
            {
                Response.Redirect("ReconSignIn.aspx");
            }

            lblCustmerName.Text = ((User)Session["CurrentUserVO"]).CustomerName; 
            //txtCustomerId.ReadOnly = true;
            if (!IsPostBack)
            {
                loadRoles();
                bntbrowseRemitter.Enabled = false;
                //bntbrowse.Enabled = false;
                //bntgetdetails.Enabled = false;
                //txtPassword.Text = "";
                //txtPassword.Enabled = true;
                //rbOption.Focus();
                BindGrid();
            }
        }
        public void BindGrid()
        {
            UserEntity usrEntity = new UserEntity();
            List<User> lstUser = null;

            try
            {
                lstUser = usrEntity.GetUserDetailsByUserId("", ((User)Session["CurrentUserVO"]).CustomerID);

                if (lstUser == null)
                {
                    gvCustomer.DataSource = null;
                    gvCustomer.DataBind();
                }
                else
                {
                    gvCustomer.DataSource = lstUser;
                    gvCustomer.DataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string resp = string.Empty;
            UserEntity userEntity = new UserEntity();
            List<User> lstUser = null;
            User user;
            string role_id = string.Empty;
            string role_type = "";
            string[] arr = new string[2];
            arr = ddlUserType.SelectedValue.ToString().Split('-');
            role_id = arr[1];
            role_type = arr[0];
            //if (ddlUserType.SelectedValue == "C")
            //    role_id = "Customer";
            //else if (ddlUserType.SelectedValue == "R")
            //    role_id = "Remitter";
            //else
            //    role_id = "System";

            //if (rbOption.SelectedValue == "1")
            //{
                lstUser = userEntity.GetUserDetailsByUserId(txtUserId.Text.Trim(), ((User)Session["CurrentUserVO"]).CustomerID);

                if (lstUser != null)
                {
                     if ((txtUserId.Text.Trim() != ((User)Session["CurrentUserVO"]).UserID))
                    {
                        user = new User
                        {
                            UserID = txtUserId.Text,
                            UserType = role_type,
                            RemitterID = txtRemitterId.Value,
                            CustomerID = ((User)Session["CurrentUserVO"]).CustomerID,
                            UserName = txtUserName.Text,
                            RoleID = role_id,
                            EmailAddress = txtEmail.Text,
                            MobileNumber = txtMobileNumber.Text,
                            IsEnabled = chkEnable.Checked,
                            IsLocked = chkLock.Checked,
                            IsActive = true,//chkActive.Checked,
                            IsDomainUser = false
                        };
                        int retval = userEntity.ModifyUser(user, ((User)Session["CurrentUserVO"]).UserID);
                        if (retval != 0)
                        {
                            lblMessage.Text = "User modified successfully!";
                            btnClickPopup.Show();
                            ResetFields();
                        }
                        else
                        {
                            lblMessage.Text = "Error Modifying user!";
                            btnClickPopup.Show();
                        }
                    }
                }
                else
                {
                    user = new User
                    {
                        UserID = txtUserId.Text,
                        UserType = role_type,
                        RemitterID = txtRemitterId.Value,
                        CustomerID = ((User)Session["CurrentUserVO"]).CustomerID,//txtCustomerId.Text,
                        UserName = txtUserName.Text,
                        RoleID = role_id,
                        EmailAddress = txtEmail.Text,
                        MobileNumber = txtMobileNumber.Text,
                        IsEnabled = chkEnable.Checked,
                        IsLocked = chkLock.Checked,
                        IsActive = true,//chkActive.Checked,
                        IsDomainUser = false,
                    };
                    int retval = userEntity.RegisterUser(user, ((User)Session["CurrentUserVO"]).UserID);

                    if (retval != 0)
                    {
                        lblMessage.Text = "User added successfully!";
                        btnClickPopup.Show();
                        ResetFields();
                    }
                    else
                    {
                        lblMessage.Text = "Error adding user!";
                        btnClickPopup.Show();
                    }
                }
                BindGrid();
            /*}
            else
            {
                lstUser = userEntity.GetUserDetailsByUserId(txtUserId.Text.Trim(), ((User)Session["CurrentUserVO"]).CustomerID);
                if (lstUser == null)
                {
                        lblMessage.Text = "User does not exist!";
                        btnClickPopup.Show();
                }
                else
                {
                   
                }
            }*/
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ResetFields();
        }

        private void ResetFields()
        {
            //rbOption.SelectedValue = "1";
            //bntgetdetails.Enabled = false;
            //bntbrowse.Enabled = false;
            txtUserId.Text = "";
			ddlUserType.ClearSelection();
            ddlUserType.SelectedValue = "0";
            txtRemitterId.Value = "";
            btnSubmit.Text = "Add";
            //txtCustomerId.Text = "";
            txtUserName.Text = "";
           // txtPassword.Text = "";
            txtEmail.Text = "";
            txtMobileNumber.Text = "";
            chkEnable.Checked = true;
            //chkActive.Checked = true;
            chkLock.Checked = false;
        }

        //protected void imgbtnSearch_Click(object sender, ImageClickEventArgs e)
        //{
        //    Session["UserSearch"] = txtUserId.Text.ToString().Trim();
        //    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<SCRIPT>window.open('SearchUser.aspx', '_Parent', 'height=400, width=650, left=300, top=150, location=no, menubar=no, resizable=no,scrollbars=no, titlebar=no, toolbar=no',false);</SCRIPT>");
        //}

        //protected void bntgetdetails_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        if (txtUserId.Text.Trim() != "")
        //        {
        //            UserEntity userEntity = new UserEntity();
        //            //User user;
        //            List<User> lstUser = null;
        //            lstUser = userEntity.GetUserDetailsByUserId(txtUserId.Text.Trim(), ((User)Session["CurrentUserVO"]).CustomerID);

        //            if (lstUser == null)
        //            {
        //                lblMessage.Text = "No record found for this user!";
        //                btnClickPopup.Show();
        //            }
        //            else
        //            {
        //                if (lstUser.Count == 1)
        //                {
        //                    foreach (User user in lstUser)
        //                    {                            
        //                        ResetFields();
        //                        ddlUserType.ClearSelection();
        //                        // ddlUserType.Items.FindByValue(dtUserDetails.Rows[0].ItemArray[1].ToString() + "-" + dtUserDetails.Rows[0].ItemArray[6].ToString()).Selected = true;
        //                        ddlUserType.Items.FindByValue(user.UserType + "-" + user.RoleID).Selected = true;
        //                        //ddlUserType.ClearSelection();
        //                        //ddlUserType.Items.FindByValue(user.UserType).Selected = true;
        //                        txtUserId.Text = user.UserID;
        //                        txtRemitterId.Value = user.RemitterID;
        //                        //txtCustomerId.Text = user.CustomerID;
        //                        lblCustmerName.Text = ((User)Session["CurrentUserVO"]).CustomerName;
        //                        txtUserName.Text = user.UserName;
        //                        txtEmail.Text = user.EmailAddress;
        //                        txtMobileNumber.Text = user.MobileNumber;
        //                        chkEnable.Checked = user.IsEnabled;
        //                        chkLock.Checked = user.IsLocked;
        //                        //chkActive.Checked = user.IsActive;

        //                        rbOption.SelectedValue = "2";
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {
        //            lblMessage.Text = "Enter User ID!";
        //            btnClickPopup.Show();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //}

        //protected void bntbrowse_Click(object sender, EventArgs e)
        //{
        //    string path;
        //    path = "UserMaster.aspx";
        //    // txtUserId.Text - Get the value ctl00$BodyHolder$txtUserId from Unique Id of the control txtUserId
        //    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<SCRIPT>window.open('SearchUser.aspx?textbox=" + txtUserId.Text + "&PageRequest= " + path + "','cal','height=400, width=650, left=300, top=150, location=no, menubar=no, resizable=no,scrollbars=no, titlebar=no, toolbar=no',false);</SCRIPT>");
        //}

        protected void btnok_Click(object sender, EventArgs e)
        {
            btnClickPopup.Hide();
        }

        //protected void rbOption_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    if (rbOption.SelectedValue.Trim() == "1")
        //    {
        //        bntbrowse.Enabled = false;
        //        bntgetdetails.Enabled = false;
        //        //txtPassword.Text = "";
        //        //txtPassword.Enabled = true;
        //    }
        //   else 
        //    {
        //        bntbrowse.Enabled     = true;
        //        bntgetdetails.Enabled = true;
        //        //txtPassword.Text = "";
        //        //txtPassword.Enabled = false;
        //    }
        //}

        protected void bntbrowseRemitter_Click(object sender, EventArgs e)
        {
            string path;
            path = "UserMaster.aspx";
            // txtUserId.Text - Get the value ctl00$BodyHolder$txtUserId from Unique Id of the control txtUserId
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<SCRIPT>window.open('SearchRemitter.aspx?textbox=" + txtRemitterId.Value + "&PageRequest= " + path + "','cal','height=400, width=650, left=300, top=150, location=no, menubar=no, resizable=no,scrollbars=no, titlebar=no, toolbar=no',false);</SCRIPT>");
        }

        private void loadRoles()
        {
            RoleEntity roleEntity = new RoleEntity();
            List<UserRole> roleLst = null;
            try
            {
                //Role_Id,Role_Desc,Role_Type,Is_Enabled
                roleLst = roleEntity.GetAllRoles(((User)Session["CurrentUserVO"]).UserType == "S", ((User)Session["CurrentUserVO"]).CustomerID);

                if (roleLst != null && roleLst.Count > 0)
                {
                    ddlUserType.Items.Insert(0, "Select Role Type");
                    ddlUserType.Items[0].Value = "0";

                    for (int i = 0; i < roleLst.Count; i++)
                    {
                        UserRole role = roleLst[i];
                        ddlUserType.Items.Add(role.RoleDescription.Trim());
                        ddlUserType.Items[i + 1].Value = (role.RoleType.Trim() + "-" + role.RoleID.Trim());
                    }
                }

            }
            catch (Exception exc)
            {
                if (exc != null)
                {
                    throw;
                }
            }
            finally
            {
                roleLst = null;
                roleEntity = null;
            }

        }

        protected void gvCustAccount_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int retval = 0;
            try
            {
                Label userId = ((Label)gvCustomer.Rows[e.RowIndex].Cells[1].FindControl("lblUserID"));
                UserEntity userEntity = new UserEntity();
                retval = userEntity.DeleteUser(Convert.ToString(userId.Text));
                if (retval != 0)
                {
                    lblMessage.Text = "User deleted successfully!";
                    btnClickPopup.Show();
                }
                else
                {
                    lblMessage.Text = "Error in deleting user detail!";
                    btnClickPopup.Show();
                }
            }
            catch
            {

            }
            BindGrid();
        }

        protected void ddlUserType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string userType = string.Empty;
            userType = ddlUserType.SelectedValue;

            if (userType.Substring(0, 1) == "R")
            {
                bntbrowseRemitter.Enabled = true;
                txtRemitterId.Value = "";
            }
            else
            {
                bntbrowseRemitter.Enabled = false;
                txtRemitterId.Value = "";
            }
        }
    }
}